import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Cookies from 'js-cookie';

function useInactivityTimeout(timeoutMs = 3600000) {
    const navigate = useNavigate();

    useEffect(() => {
        let inactivityTimer;

        const resetInactivityTimer = () => {
            clearTimeout(inactivityTimer);
            inactivityTimer = setTimeout(logoutUser, timeoutMs);
        };

        const logoutUser = () => {
            // 清理计时器和监听器
            clearTimeout(inactivityTimer);
            window.removeEventListener('mousemove', resetInactivityTimer);
            window.removeEventListener('keydown', resetInactivityTimer);

            // 清除登录状态
            localStorage.removeItem("menus");
            localStorage.removeItem("isLoggedIn");
            localStorage.removeItem("authButtons");
            Cookies.remove('authToken', { path: '/' });

            console.log("某页面-用户长时间未操作，已自动登出");
            // 跳转到登录页
            navigate('/login');
        };

        window.addEventListener('mousemove', resetInactivityTimer);
        window.addEventListener('keydown', resetInactivityTimer);

        resetInactivityTimer();

        return () => {
            clearTimeout(inactivityTimer);
            window.removeEventListener('mousemove', resetInactivityTimer);
            window.removeEventListener('keydown', resetInactivityTimer);
        };
    }, [navigate, timeoutMs]);
}


export default function Page4() {


    useInactivityTimeout(10000); // 10s未操作自动跳转登录页

    return <div>

        <h2>
            这是菜单项4对应的页面内容
        </h2>

        <p>
            这里是一些静态内容，您可以根据需要进行修改。
        </p>

    </div>;
}